<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>排序的几种方法</title>
  </head>
  <body>
    <script>
      /* sort()排序 */
      const arr = [1, 3, 2, 7, 11, 44, 32, 5, 100, 78, 66, 9, 8]
      arr.sort() //[1, 100, 11, 2, 3, 32, 44, 5, 66, 7, 78, 8, 9]
      arr.sort(function (a, b) {
        return a - b
      }) //[1, 2, 3, 5, 7, 8, 9, 11, 32, 44, 66, 78, 100]
      arr.sort(function (a, b) {
        return b - a
      }) //[100, 78, 66, 44, 32, 11, 9, 8, 7, 5, 3, 2, 1]
      /* 冒泡排序 */
      function bubbleSort(
        arr = [11, 2, 4, 3, 88, 90, 56, 33, 76, 100, 99, 60, 44]
      ) {
        for (let i = 0; i < arr.length - 1; i++) {
          for (let j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
              [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
            }
          }
        }
        return arr
      }
      /* 快速排序 */
      function quickSort(arr) {
        if (arr.length <= 1) {
          return arr
        }
        let pivotIndex = Math.floor(arr.length / 2)
        let pivot = arr.splice(pivotIndex, 1)[0]
        let left = []
        let right = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] < pivot) {
            left.push(arr[i])
          } else {
            right.push(arr[i])
          }
        }
        return quickSort(left).concat([pivot], quickSort(right))
        //return [...quickSort(left), pivot, ...quickSort(right)]
      }
      /* 选择排序 */
      function selectSort(arr) {
        for(let i = 0; i < arr.length - 1; i++) {
          let index = i
          for(let j = i + 1; j < arr.length; j++) {
            if(arr[j] < arr[index]) {
              index = j
            }
          }
          [arr[i], arr[index]] = [arr[index], arr[i]]
        }
        return arr
      }
    </script>
  </body>
</html>
